package com.yuexunit.mobilenurse.module.SignInput.ui;

import android.content.Context;
import android.content.Intent;
import android.text.InputType;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;

import com.yuexunit.mobilenurse.R;
import com.yuexunit.mobilenurse.base.AppContext;
import com.yuexunit.mobilenurse.config.AppConfig;
import com.yuexunit.mobilenurse.module.SignInput.adapter.SignTypeAdapter;
import com.yuexunit.mobilenurse.module.SignInput.bean.Sign_Single;
import com.yuexunit.mobilenurse.module.SignInput.bean.Sign_Single_Check;
import com.yuexunit.mobilenurse.module.SignInput.bean.Sqlite_SignInputBean;
import com.yuexunit.mobilenurse.module.SignInput.model.impl.SignModel;
import com.yuexunit.mobilenurse.module.SignInput.presenter.impl.SignPresenter;
import com.yuexunit.mobilenurse.module.SignInput.ui.view.ISignInput;
import com.yuexunit.mobilenurse.widget.FixedSwipeListView;

import org.kymjs.kjframe.KJActivity;
import org.kymjs.kjframe.ui.ViewInject;
import org.kymjs.kjframe.utils.PreferenceHelper;
import org.kymjs.kjframe.utils.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by sslcjy on 16/1/26.
 */
public class Act_Signs_Input extends KJActivity implements ISignInput {

    @Bind(R.id.signinput_bedno)
    public TextView signinput_bedno;
    @Bind(R.id.signinput_name)
    public TextView signinput_name;
    @Bind(R.id.signinput_visitno)
    public TextView signinput_visitno;
    @Bind(R.id.sign_time_day)
    public TextView sign_time_day;
    @Bind(R.id.sign_time_hour)
    public Spinner sign_time_hour;
    @Bind(R.id.types_list)
    FixedSwipeListView typesList;
    @Bind(R.id.type_edit_in)
    EditText typeEditIn;
    @Bind(R.id.type_edit_out)
    EditText typeEditOut;
    @Bind(R.id.sign_temp_spinner)
    Spinner signTempSpinner;
    @Bind(R.id.sign_temp_edt)
    EditText signTempEdt;
    @Bind(R.id.type_pulse_edit)
    EditText typePulseEdit;
    @Bind(R.id.type_pain_edit)
    EditText typePainEdit;
    @Bind(R.id.type_breath_edit)
    EditText typeBreathEdit;
    @Bind(R.id.type_shit_edit)
    EditText typeShitEdit;

    private SignPresenter presenter;

    //病人相关信息
    public String inpNo;//住院号
    public String recorder;//记录人员姓名
    public String name;//病人姓名
    public Sqlite_SignInputBean currentbean;//存入数据库的当前病人相关信息
    public String sign_hour;//输入病人的时间
    public String temp;//体温类型
    //体征显示界面的adpater
    private SignTypeAdapter adapter;
    //当前体征显示界面的列表所含数据
    public ArrayList<Sign_Single_Check> arrayList = new ArrayList<Sign_Single_Check>();
    public ArrayList<String> BasicTypesNames = new ArrayList<String>();
    //从体征添加列表处传过来的体征项
    public Sign_Single_Check addtype;

    //病区号
    private String Wardno;

    private String[] temp_code;

    @Override
    public void setRootView() {
        setContentView(R.layout.act_signs_input);
        ButterKnife.bind(this);
    }

    @Override
    public void initData() {
        super.initData();

        presenter = new SignPresenter(new SignModel(), this);
        temp_code = this.getResources().getStringArray(R.array.temp_code);
        Wardno = PreferenceHelper.readString(aty, AppConfig.NURSE_INFO, AppConfig.NURSE_WARDNO_ID);
        inpNo = PreferenceHelper.readString(aty, AppConfig.CURRENT_PATIENT_INFO, AppConfig.CURRENT_PATIENT_VISITNO);
        recorder = PreferenceHelper.readString(aty, AppConfig.NURSE_INFO, AppConfig.NURSE_LOGID);
        name = PreferenceHelper.readString(aty, AppConfig.CURRENT_PATIENT_INFO, AppConfig.CURRENT_PATIENT_NAME);
        initBaseTypes();
    }

    private void initBaseTypes() {
        ArrayList<Sign_Single> singleTypes = ((AppContext) getApplication()).getSingleTypes();
        if (singleTypes.size() > 0) {
            for (int i = 0; i < singleTypes.size(); i++) {
                Sign_Single_Check sign_single_check = new Sign_Single_Check();
                sign_single_check.setCode(singleTypes.get(i).getCode());
                sign_single_check.setName(singleTypes.get(i).getName());
                sign_single_check.setUnit(singleTypes.get(i).getUnit());
                sign_single_check.setIscheck(false);
                arrayList.add(sign_single_check);
            }
        }
        if (arrayList.size() > 0) {
            for (int i = 0; i < arrayList.size(); i++) {
                BasicTypesNames.add(arrayList.get(i).getCode());
            }
            adapter = new SignTypeAdapter(typesList, arrayList, R.layout.item_type);
            typesList.setAdapter(adapter);
        } else {
            adapter = new SignTypeAdapter(typesList, arrayList, R.layout.item_type);
            typesList.setAdapter(adapter);
        }
    }

    @Override
    public void initWidget() {
        super.initWidget();
        signinput_name.setText(PreferenceHelper.readString(aty, AppConfig.CURRENT_PATIENT_INFO, AppConfig.CURRENT_PATIENT_NAME));
        signinput_bedno.setText(PreferenceHelper.readString(aty, AppConfig.CURRENT_PATIENT_INFO, AppConfig.CURRENT_PATIENT_BEDCODE));
        signinput_visitno.setText(inpNo);
        sign_time_day.setText(StringUtils.getDataTime("yyyy-MM-dd"));
        sign_time_hour.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                sign_hour = (String) parent.getItemAtPosition(position);
                PreferenceHelper.write(aty, AppConfig.SIGN_INFO, AppConfig.SIGN_TIME, position);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        sign_time_hour.setSelection(PreferenceHelper.readInt(aty, AppConfig.SIGN_INFO, AppConfig.SIGN_TIME));


        signTempSpinner.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                temp = temp_code[position];
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        typeEditIn.setInputType(InputType.TYPE_CLASS_PHONE);
        typeEditOut.setInputType(InputType.TYPE_CLASS_PHONE);
        signTempEdt.setInputType(InputType.TYPE_CLASS_PHONE);
        typePulseEdit.setInputType(InputType.TYPE_CLASS_PHONE);
        typePainEdit.setInputType(InputType.TYPE_CLASS_PHONE);
        typeBreathEdit.setInputType(InputType.TYPE_CLASS_PHONE);
        typeShitEdit.setInputType(InputType.TYPE_CLASS_PHONE);

    }

    @OnClick(R.id.add_type)
    public void addTypes() {
        Intent intent = new Intent(Act_Signs_Input.this, Act_AddType.class);
        aty.startActivityForResult(intent, 1);
    }

    @OnClick(R.id.titlebar_img_back)
    public void out() {
        finish();
    }

    @OnClick({R.id.titlebar_img_menu, R.id.right_text})
    public void uploadMenu() {
        if (adapter != null) {
            presenter.buildUploadSignValue((HashMap) adapter.getEditValue(), (HashMap) adapter.getEditBooldValue(), arrayList);
//            adapter.cleatMap();
//            adapter.notifyDataSetChanged();
        } else {
            ViewInject.toast("请检查网络连接...");
        }
//        finish();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        switch (resultCode) { //resultCode为回传的标记，我在B中回传的是RESULT_OK
            case RESULT_OK:
                ArrayList list = data.getExtras().getParcelableArrayList("addtypelist");
                ArrayList<Sign_Single_Check> addTypes = (ArrayList<Sign_Single_Check>) list.get(0);
//                Iterator it = addTypes.iterator();
//                while (it.hasNext()) {
//                    addtype = (Sign_Single_Check) it.next();
//                    if (BasicTypesNames.contains(addtype.getCode())) {
//                        it.remove();
//                    }
//                }
//                arrayList.addAll(addTypes);
//                BasicTypesNames.clear();
//                for (int i = 0; i < arrayList.size(); i++) {
//                    BasicTypesNames.add(arrayList.get(i).getCode());
//                }
                arrayList.clear();
                for (int i = 0; i < addTypes.size(); i++) {
                    if (addTypes.get(i).getIscheck())
                        arrayList.add(addTypes.get(i));
                }
                if (adapter != null) {
                    adapter.refresh(arrayList);
                } else {
                    adapter = new SignTypeAdapter(typesList, arrayList, R.layout.item_type);
                    typesList.setAdapter(adapter);
                }
                ArrayList<Sign_Single> sign_singles = new ArrayList<Sign_Single>();
                for (int j = 0; j < arrayList.size(); j++) {
                    Sign_Single sign_single = new Sign_Single();
                    sign_single.setCode(arrayList.get(j).getCode());
                    sign_single.setName(arrayList.get(j).getName());
                    sign_single.setUnit(arrayList.get(j).getUnit());
                    sign_singles.add(sign_single);
                }
                ((AppContext) getApplication()).setSingleTypes(sign_singles);
                break;
            default:
                break;
        }
    }

    @Override
    public void showSignInputType(ArrayList<Sign_Single> baselist) {
        for (int i = 0; i < baselist.size(); i++) {
            Sign_Single_Check sign_single_check = new Sign_Single_Check();
            sign_single_check.setCode(baselist.get(i).getCode());
            sign_single_check.setName(baselist.get(i).getName());
            sign_single_check.setUnit(baselist.get(i).getUnit());
            sign_single_check.setIscheck(false);
            arrayList.add(sign_single_check);
        }
        adapter = new SignTypeAdapter(typesList, arrayList, R.layout.item_type);
        typesList.setAdapter(adapter);
    }

    @Override
    public void uploadSignValue(String buildItem) {
        StringBuilder builder = new StringBuilder();
        if (!(StringUtils.isEmpty(typeEditIn.getText()) && StringUtils.isEmpty(typeEditOut.getText()))) {
            builder.append("427:" + typeEditIn.getText() + "/" + typeEditOut.getText());
        }

        if (!StringUtils.isEmpty(signTempEdt.getText())) {
            if (builder.length() != 0) {
                builder.append("," + temp + ":" + signTempEdt.getText());
            } else {
                builder.append(temp + ":" + signTempEdt.getText());
            }
        }

        if (!StringUtils.isEmpty(typePulseEdit.getText())) {
            if (builder.length() != 0) {
                builder.append("," + "8" + ":" + typePulseEdit.getText());
            } else {
                builder.append("8" + ":" + typePulseEdit.getText());
            }
        }

        if (!StringUtils.isEmpty(typePainEdit.getText())) {
            if (builder.length() != 0) {
                builder.append("," + "421" + ":" + typePainEdit.getText());
            } else {
                builder.append("421" + ":" + typePainEdit.getText());
            }
        }

        if (!StringUtils.isEmpty(typeBreathEdit.getText())) {
            if (builder.length() != 0) {
                builder.append("," + "18" + ":" + typeBreathEdit.getText());
            } else {
                builder.append("18" + ":" + typeBreathEdit.getText());
            }
        }

        if (!StringUtils.isEmpty(typeShitEdit.getText())) {
            if (builder.length() != 0) {
                builder.append("," + "3" + ":" + typeShitEdit.getText());
            } else {
                builder.append("3" + ":" + typeShitEdit.getText());
            }
        }

        if (builder.length() != 0 && !buildItem.isEmpty()) {
            builder.append("," + buildItem);
        } else {
            builder.append(buildItem);
        }
        //buildItem是病人的体征id及体征值
        Map<String, String> params = new HashMap<>();
        params.put("inpNo", inpNo);
        params.put("timestamp", System.currentTimeMillis() + "");
        params.put("recorder", recorder);
        params.put("signData", builder.toString());
        params.put("timepoint", StringUtils.getDataTime("yyyy-MM-dd") + " " + sign_hour + ":00:00");
        presenter.uploadTypesInfo(params, name);
    }

    /**
     * 通过dispatchTouchEvent每次ACTION_DOWN事件中动态判断非EditText本身区域的点击事件，然后在事件中进行屏蔽。然后当点击不是EditText时候，进行隐藏键盘操作
     *
     * @param ev
     * @return
     */

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideInput(v, ev)) {

                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
            }
            return super.dispatchTouchEvent(ev);
        }
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);
    }

    public boolean isShouldHideInput(View v, MotionEvent event) {

        if (v != null && (v instanceof EditText)) {
            int[] leftTop = {0, 0};
            //获取输入框当前的location位置
            v.getLocationInWindow(leftTop);
            int left = leftTop[0];
            int top = leftTop[1];
            int bottom = top + v.getHeight();
            int right = left + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                // 点击的是输入框区域，保留点击EditText的事件\
                return false;
            } else {
                return true;
            }
        }
        return false;
    }

}
